<?php

function cust_php_add_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			$T['ss']['cust_php'] = 'Custom php.ini';
			$T['custom_php'] = 'Custom PHP';
			break;
	}
}

function cust_php_add_cfg(&$cfg) {
	global $cfg;
	if (!stristr($cfg['sslang'], 'cust_php')) {
		$cfg['sslang'].=",cust_php";
	}
}

function cust_php_generate_host_conf(&$data){

	if ($data['serverside']['cust_php'] != 'on') {
		return false;
	} 

	global $cfg;

    $php_ini_sys_fs="apc.enabled,apc.include_once_override,apc.localcache,apc.report_autofilter,apc.rfc1867,apc.write_lock,cgi.discard_path,cgi.check_shebang_line,cgi.fix_pathinfo,cgi.force_redirect,com.allow_dcom,enable_dl,fbsql.generate_warnings,fastcgi.logging,fbsql.allow_persistant,fbsql.allow_persistent,fbsql.autocommit,file_uploads,htscanner.stop_on_error,hyerwave.allow_persistent,hyperwave.allow_persistent,http.request.datashare.dns,ibase.allow_persistent,ifx.allow_persistent,ingres.allow_persistent,mssql.allow_persistent,mysql.allow_local_infile,mysql.allow_persistent,mysqli.allow_local_infile,mysqlnd.collect_statistics,odbc.allow_persistent,odbc.check_persistent,pgsql.allow_persistent,session_pgsql.create_table,sybct.allow_persistent,vld.execute,xdebug.extended_info,mime_magic.debug,mssql.secure_connection,mysqli.reconnect,oci8.old_oci_close_semantics,oci8.privileged_connect,runkit.internal_override,safe_mode,safe_mode_gid,session_pgsql.disable,session_pgsql.failover_mode,session_pgsql.keep_expired,session_pgsql.serializable,session_pgsql.short_circuit,session_pgsql.use_app_vars,sql.safe_mode,unicode.semantics,vld.active,vld.skip_append,vld.skip_prepend,xmlrpc_errors";
    $php_ini_sys_f=explode(",",$php_ini_sys_fs);

    $php_ini_sys_vs="apc.enable_cli,apc.rfc1867_freq,apc.slam_defense,apc.shm_segments,apc.stat,apc.stat_ctime,apc.ttl,apc.user_ttl,fastcgi.impersonate,fbsql.show_timestamp_decimals,http.request.datashare.connect,http.request.datashare.cookie,http.request.datashare.ssl,ibm_db2.i5_allow_commit,ibm_db2.i5_dbcs_alloc,pgsql.auto_reset_persistent,apc.filters,apc.mmap_file_mask,browscap,cgi.redirect_status_env,doc_root,fbsql.default_host,ibase.default_db,ibm_db2.instance_name,ifx.default_host,ifx.default_password,ifx.default_user,pdo_odbc.db2_instance_name,safe_mode_include_dir,upload_tmp_dir,user_dir";
    $php_ini_sys_v=explode(",",$php_ini_sys_vs);

    $php_ini_flagss="allow_url_include,always_populate_raw_post_data,apd.statement_tracing,asp_tags,assert.bail,assert.quiet_eval,async_send,auto_detect_line_endings,cgi.nph,child_terminate,com.autoregister_typelib,com.autoregister_verbose,define_syslog_variables,display_startup_errors,gd.jpeg_ignore_warning,http.ob_deflate_auto,http.ob_deflate_flags,http.ob_inflate_auto,http.ob_inflate_flags,http.only_exceptions,http.send.deflate.start_auto,http.send.deflate.start_flags,http.send.inflate.start_auto,http.send.inflate.start_flags,ifx.byteasvarchar,ifx.charasvarchar,ifx.nullformat,ifx.textasvarchar,ignore_repeated_errors,ignore_repeated_source,ignore_user_abort,implicit_flush,ingres.cursor_mode,ingres.trace_connect,last_modified,log_errors,magic_quotes_runtime,magic_quotes_sybase,mbstring.encoding_translation,mbstring.strict_detection,mssql.batchsize,mssql.compatability_mode,mysql.trace_mode,namazu.debugmode,namazu.loggingmode,odbtp.detach_default_queries,register_globals,session.auto_start,session.use_trans_sid,tidy.clean_output,track_errors,valkyrie.auto_validate,xbithack,zend.ze1_compatibility_mode,allow_call_time_pass_reference,allow_url_fopen,apc.cache_by_default,assert.active,assert.warning,auto_globals_jit,axis2.enable_exception,axis2.enable_trace,bcompiler.enabled,com.autoregister_casesensitive,detect_unicode,engine,expect.loguser,html_errors,http.force_exit,http.send.not_found_404,ingres.report_db_warnings,magic_quotes_gpc,memcache.allow_failover,msql.allow_persistent,odbtp.truncation_errors,phar.readonly,phar.require_hash,register_argc_argv,register_long_arrays,report_memleaks,report_zend_debug,session.bug_compat_42,session.bug_compat_warn,session.use_cookies,session.use_only_cookies,short_open_tag,soap.wsdl_cache_enabled,sqlite.iso8859.locale,sybase.allow_persistent,track_vars,y2k_compliance,coin_acceptor.auto_initialize,coin_acceptor.command_function,coin_acceptor.lock_on_close,coin_acceptor.auto_reset,coin_acceptor.autoreset,coin_acceptor.start_unlocked,session.cookie_httponly,session.cookie_secure";

    $php_ini_flags=explode(",",$php_ini_flagss);

    $php_ini_locked=explode(",",$cfg['php_locked_settings']);

    $php_ini_only=array("expose_php",
                      "extension",
                      "disable_classes",
                      "disable_functions",
                      "mail.force_extra_parameters");

	// Check for ServerSide Options (PHP, Perl, ASP, Python, etc)
	$cfgsslangarr = explode(',',$cfg['sslang']);
	foreach ($cfgsslangarr as $ssoption) {
              // make sure php is active before allowing php settings to be added to the config.
              if ($data['serverside']['php'] == 'on' AND $cfg['ss'][$ssoption]) $php_ssoptions[]=$ssoption;
	}

	// Parse %PATH% for real path. (used in php serverside config)
	if ($data['type'] == 'pointer') {
		$httpdconf = str_replace("%PATH%",$cfg['webdir']."/".$data['owner'],$httpdconf);
	} else {
		$httpdconf = str_replace("%PATH%",$data['path'],$httpdconf);
	}
	
    unset($ssoption);

    if(isset($php_ssoptions)){
    
        //check if _php directory exists. if not create and move the correct template to it.
        if(!is_dir($data['path']."/_php")){
            mkdir($data['path']."/_php", 0755);
            chmod($data['path']."/_php", 0755);
            chown($data['path']."/_php","root");
            chgrp($data['path']."/_php","g".$data['id']);
        }
    
        foreach($cfg['php_active'] as $php_active){
        
            switch($php_active) {
            	case 'PHP5CGI':
            		$phpini = "php5-cgi.ini";
                	$phptpl = "php5-cgi.httpd.tpl";
                    break;
                case 'PHP4CGI':
                	$phpini = "php4-cgi.ini";
                	$phptpl = "php4-cgi.httpd.tpl";
                    break;
                case 'mod_php5':
                	$phpini = "mod_php5.ini";
                	$phptpl = "mod_php5.httpd.tpl";
                	break;
                case 'mod_php4':
                	$phpini = "mod_php4.ini";
                	$phptpl = "mod_php4.httpd.tpl";
                	break;
                default:
                	break;
			}
			
            if (!file_exists($data['path']."/_php/".$phpini)) {
                copy($cfg['basedir']."/httpd/templates/".$phptpl, $data['path']."/_php/".$phpini);
                chown($data['path']."/_php/".$phpini,"root");
                chgrp($data['path']."/_php/".$phpini,"g".$data['id']);
                chmod($data['path']."/_php/".$phpini, 0770);
            }
            
            switch($php_active) {
            	case 'PHP5CGI':
            		if ($cfg['prog']['php5-cgi'] != "") {
	            		$php5cgi_ssoptions = "\t<IfDefine PHP5CGI>\n";
	                    $php5cgi_ssoptions.= "\t\tScriptAlias /php5-cgi ".$cfg['prog']['php5-cgi']." -c ".$data['path']."/_php/".$phpini."\n";
	                    $php5cgi_ssoptions.= "\t\tAction php5-cgi /php5-cgi
	    									 \t\tAddHandler php5-cgi .php .phps
	    									 \t</IfDefine>\n\n";
	                    $ssoptions.= $php5cgi_ssoptions;
                    } else {
                    	$ssoptions.= '# PHP5CGI disabled because the executable is not defined';
                    }
                    break;
                case 'PHP4CGI':
                	if ($cfg['prog']['php5-cgi'] != "") {
	                	$php4cgi_ssoptions = "\<IfDefine PHP4CGI>\n";
	                    $php4cgi_ssoptions.= "\t\tScriptAlias /php4-cgi ".$cfg['prog']['php4-cgi']." -c ".$data['path']."/_php/".$phpini."\n";
	                    $php4cgi_ssoptions.= "\t\tAction php4-cgi /php4-cgi
	    									 \t\tAddHandler php4-cgi .php4
	    									 \t</IfDefine>\n\n";
	                    $ssoptions.= $php4cgi_ssoptions;
                    } else {
                    	$ssoptions.= '# PHP4CGI disabled because the executable is not defined';
                    }
                    break;
                case 'mod_php5':
                case 'mod_php4':
                	$ini_arr = parse_ini_file($data['path']."/_php/".$phpini);
                
	                foreach($ini_arr as $key => $value){
	                    
	                    if ($data['type'] == 'pointer') {
	                    	$value = str_replace("{PATH}",$cfg['webdir']."/".$data['owner'],$value);
	                    } else {
	                    	$value = str_replace("{PATH}",$data['path'],$value);
	                    }
	                    
	                    $value=str_replace("{PHP_LIB}",$cfg['php_lib'],$value);
	                    
	                    if ($value == "" || in_array($key,$php_ini_only) || in_array($key,$php_ini_locked)) {
	                    	unset($ini_arr[$key]);
	                    } elseif (in_array($key,$php_ini_sys_f) || in_array($key,$php_ini_sys_v)) {
	                        if (in_array($key,$php_ini_sys_f) || in_array($key,$php_ini_flags)) {
	                        	$php_options.="\t\tphp_admin_flag ".$key." ".$value."\n";
	                        } else {
	                        	$php_options.="\t\tphp_admin_value ".$key." ".$value."\n";
	                        }
	                        
	                    } elseif (in_array($key,$php_ini_flags)) {
	                    	$php_options.="\t\tphp_flag ".$key." ".$value."\n";
	                    } else {
	                    	$php_options.="\t\tphp_value ".$key." ".$value."\n";
	                    }
	                }
	                
	                if($data['serverside']['PHP_SafeMode_Off'] == 'on') {
	                	$php_options.="\t\tphp_admin_flag safe_mode off\n\t\tphp_admin_flag register_globals on\n";
	                }
	                
	                $ssoptions.="\t<IfModule ".$php_active.".c>\n".$php_options."\n\t</IfModule>\n\n";
	                break;
	            default:
	            	break;
	        }
	        
            return $ssoptions;
        }
    }
}

function  cust_php_template(&$ret) {
	global $cfg;

	$template['title'] = 'custom_php';
	$template['servicename'] = 'httpd';
	$template['active'] = true;
	$template['file'][] = array('filename' => 'mod_php5');
	$template['file'][] = array('filename' => 'mod_php4');
	$template['file'][] = array('filename' => 'php5-cgi');
	$template['file'][] = array('filename' => 'php4-cgi');
	
	$ret[] = $template;

}

?>
